import { useStore } from 'vuex';
/**
 * @description: 获取后缀
 * @param: 字符串 str 校验的字符串
 */
import dayjs from 'dayjs';
import type { FormInstance } from 'element-plus';

interface City {
    id: number;
    childList?: City[];
}
export function getSuffix(str: string): string {
    if (!str) {
        return '';
    }
    const strSuffix = str.substr(str.lastIndexOf('.') + 1);
    return strSuffix;
}

// http替换成https
export function getPdfArrayBufferNew(url: string): string {
    const protocol = window.location.protocol;
    if (protocol === 'https:' && url.indexOf(protocol) === -1) {
        return url.replace('http:', 'https:');
    }
    return url;
}

/**
 * 下载（pdf,图片直接打开）
 * @param {*} url
 * @param {*} param1 allNew=表示全部新打开窗口，name是文件名
 */
export function downLoadCommon(url: string, { allNew, name } = { allNew: true, name: '' }) {
    const a = document.createElement('a');
    const event = new MouseEvent('click');
    console.log(url);
    a.download = name || url.substring(url.lastIndexOf('/') + 1).toLowerCase();
    const httpsUrl = getPdfArrayBufferNew(url);
    a.href = httpsUrl;
    const imgTypes = ['pdf', 'jpg', 'jpeg', 'png', 'img', 'txt', 'gif', 'bmp', 'psd', 'raw', 'tif', 'tiff'];
    const type = httpsUrl.substring(httpsUrl.lastIndexOf('.') + 1).toLowerCase();
    if (allNew) {
        a.target = '_blank';
    } else if (imgTypes.includes(type)) {
        a.target = '_blank';
    }
    a.dispatchEvent(event);
}

/**
 * @description: 时间格式化
 * @param: date 时间戳, 不传默认返回发当前
 * @param: fmt 格式
 */
export function getFormatDate(dateStr: string, format = 'YYYY-mm-dd') {
    let ret;
    let fmt = format;
    const date = dateStr ? new Date(dateStr) : new Date();
    const opt = {
        'Y+': date.getFullYear().toString(), // 年
        'm+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'M+': date.getMinutes().toString(), // 分
        'S+': date.getSeconds().toString(), // 秒
        'c+': date.getMilliseconds().toString(), // 毫秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
    };
    for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'));
        }
    }
    return fmt;
}

/**
 * @description: 获取文件名字
 * @param: 字符串 str 校验的字符串
 */
export function getFileName(str: string) {
    if (!str) {
        return '';
    }
    const name = str.substr(0, str.lastIndexOf('.'));
    return name;
}

export function handleWordLimit(str: string, numeral: number): string {
    if (str) {
        if (str.length > numeral) {
            return `${str.substring(0, numeral)}...`;
        }
        return `${str}`;
    }
    return '--';
}

export function getElementTop(el: HTMLElement): number {
    if (el && el.offsetParent) {
        return getElementTop(el.offsetParent as HTMLElement) + el.offsetTop;
    }
    return el && el.offsetTop;
}

export function setTableMaxHeight(id: string, num = 120): number {
    const scrollHeight = document.body.scrollHeight;
    const offsetTop = getElementTop(document.getElementById(id));
    console.log(offsetTop);
    const maxHeight = scrollHeight - offsetTop - num;
    return maxHeight;
}

export const scaleData = [
    { zoom: 19, length: 20, Pixels: 48 },
    { zoom: 18, length: 50, Pixels: 61 },
    { zoom: 17, length: 100, Pixels: 61 },
    { zoom: 16, length: 200, Pixels: 61 },
    { zoom: 15, length: 500, Pixels: 78 },
    { zoom: 14, length: 1000, Pixels: 78 },
    { zoom: 13, length: 2000, Pixels: 78 },
    { zoom: 12, length: 5000, Pixels: 99 },
    { zoom: 11, length: 10000, Pixels: 99 },
    { zoom: 10, length: 20000, Pixels: 99 },
    { zoom: 9, length: 25000, Pixels: 59 },
    { zoom: 8, length: 50000, Pixels: 59 },
    { zoom: 7, length: 100000, Pixels: 59 },
    { zoom: 6, length: 200000, Pixels: 59 },
    { zoom: 5, length: 500000, Pixels: 76 },
    { zoom: 4, length: 1000000, Pixels: 76 },
    { zoom: 3, length: 2000000, Pixels: 75 },
];

/**
 * 排序根据localeCompare排（中文会根据首字母排）
 * @param {*} prop  数据的prop
 * @param {*} rev   1是正序，-1是倒序
 */
export function sortByLocaleCompare(prop, rev) {
    return function (a, b) {
        const str1 = a[prop] || '';
        const str2 = b[prop] || '';
        return str1.localeCompare(str2) * rev;
    };
}

// 解决乘法精度问题
export function accMul(arg1, arg2) {
    if (isNaN(arg1) || isNaN(arg2)) {
        return '';
    }
    if ((!arg1 && arg1 !== 0) || (!arg2 && arg2 !== 0)) {
        return '';
    }
    let m = 0,
        s1 = arg1.toString(),
        s2 = arg2.toString();
    try {
        m += (s1.split('.')[1] || []).length;
    } catch (e) {
        console.error(e);
    }
    try {
        m += (s2.split('.')[1] || []).length;
    } catch (e) {
        console.error(e);
    }
    // eslint-disable-next-line no-extra-parens
    // eslint-disable-next-line prettier/prettier
    return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
}

// 减法精度问题
export function subMul(arg1, arg2) {
    if ((!arg1 && arg1 !== 0) || (!arg2 && arg2 !== 0)) {
        return '';
    }
    let r1, r2, m, n;
    try {
        r1 = (arg1.toString().split('.') || [])[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = (arg2.toString().split('.') || [])[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    n = r1 >= r2 ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

// 加法精度问题
export function addMul(...val) {
    let max = 0;
    let count = 0;
    for (let i = 0; i < val.length; i++) {
        const strVal = (val[i] || 0).toString();
        const index = strVal.indexOf('.');
        let num = 0;
        if (index > -1) {
            num = strVal.length - 1 - index;
            max = num > max ? num : max;
        }
    }
    for (let i = 0; i < val.length; i++) {
        count += Math.round(val[i] * Math.pow(10, max));
    }
    return count / Math.pow(10, max);
}

export function getProvinceAndCityFromRigions(rigionList: City[]) {
    rigionList.forEach((province: City) => {
        province.childList?.forEach((city) => {
            delete city.childList;
        });
    });
    return rigionList;
}

export function getAreaFromRigions(rigionList: City[], cityId: number) {
    let area: City[] = [];
    rigionList.forEach((province: City) => {
        province.childList?.forEach((city) => {
            if (city.id === +cityId) {
                area = city.childList;
            }
        });
    });
    return area;
}
export const blob2Json = async (blobData: Blob) => {
    return new Promise((resolve, reject) => {
        try {
            const reader = new FileReader();
            reader.onload = (event) => {
                const res = event.target.result;
                if (res) {
                    try {
                        const jsonData = JSON.parse(res);
                        resolve({
                            type: 'object',
                            jsonData,
                        });
                    } catch (error) {
                        resolve({
                            type: 'blob',
                        });
                    }
                } else {
                    reject();
                }
            };
            reader.readAsText(blobData);
        } catch (error) {
            reject(error);
        }
    });
};

/**
 * 从当前日期起，取一周内的星期几
 * @params( data: Number) 星期天0———星期六6
 */

export const getNearEstDate = (date = 6): string => {
    return dayjs().day(date).format('YYYY-MM-DD');
};

/**
 *
 * @param {*} url
 * @param {*} fileName 非必传，非同源环境不生效
 */
export const exportFile = (url: string, fileName = null) => {
    let link: HTMLAnchorElement | null = document.createElement('a');
    link.href = url;
    fileName && link.setAttribute('download', fileName);
    link.style.display = 'none';
    link.setAttribute('target', '_blank');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    link = null;
};

/**
 *
 * @param {*} blobData Blob实例 二进制数据流
 * @param {*} fileName 须带文件后缀名
 */

export const exportFormBlob = (data: Blob, fileName = null) => {
    // const blobData = new Blob([data], { type: 'application/vnd.ms-excel;charset=utf-8;' });
    const objectUrl = window.URL.createObjectURL(data);
    exportFile(objectUrl, fileName);
    window.URL.revokeObjectURL(objectUrl);
};
export const validateForm = (formEl: FormInstance | undefined) => {
    if (!formEl) {
        return;
    }
    return new Promise((resolve, reject) => {
        formEl.validate((valid, fields) => {
            if (valid) {
                return resolve();
            }
            reject('error submit!', fields);
            console.log('error submit!', fields);
        });
    });
};
// 校验图片宽高问题
export const checkImgInfo = (file: any) => {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.src = URL.createObjectURL(file);
        img.onload = function () {
            const width = img.width;
            const height = img.height;
            const imgData = { width, height, sizeM: file.size / 1024 / 1024, type: file.type };
            resolve(imgData);
        };
    });
};
// 按钮权限控制
export const $btnAuth = (key: string) => {
    const store = useStore();
    return store.state.puma.permissions.includes(key);
};

export const isBefore = (targetDay: string | Date, currentDay: string | Date | undefined) => {
    return dayjs(currentDay).isBefore(dayjs(targetDay), 'day');
};

export const isAfter = (targetDay: string | Date, currentDay: string | Date | undefined) => {
    return dayjs(currentDay).isAfter(dayjs(targetDay), 'day');
};

export const downloadFile = async (content: string, fileName: string) => {
    const a = document.createElement('a');
    const blob = new Blob([content]);
    const url = window.URL.createObjectURL(blob);
    a.href = url;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
};

export function copyTextToClipboard(text: string, type = 'input') {
    const input = document.createElement(type) as HTMLInputElement | HTMLTextAreaElement;
    input.setAttribute('readonly', 'readonly');
    input.value = text;
    document.body.appendChild(input);
    input.setSelectionRange(0, 9999);
    input.select();
    document.execCommand('copy');
    document.body.removeChild(input);
}

export async function writeDataToClipboard(text: string) {
    return navigator.clipboard.writeText(text);
}
